package com.pengtu.gsj.interceptor;

import java.lang.reflect.Method;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.log4j.Logger;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.pengtu.gsj.entity.app.User;
import com.pengtu.gsj.utils.UserUtils;
import com.pengtu.gsj.utils.web.SpringMvcUtils;

public class AvoidDuplicateSubmissionInterceptor extends HandlerInterceptorAdapter {
	
	public static Logger logger = Logger.getLogger(AvoidDuplicateSubmissionInterceptor.class);

	@Override
	public boolean preHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler) throws Exception {
		
		User user = UserUtils.getUser();
		if (user != null) {
			HandlerMethod handlerMethod = (HandlerMethod) handler;
			Method method = handlerMethod.getMethod();
			Token annotation = method.getAnnotation(Token.class);
			if (annotation != null) {
				boolean needSaveSession = annotation.save();
				if (needSaveSession) {
					request.getSession(true).setAttribute("token",UUID.randomUUID().toString());
				}
				boolean needRemoveSession = annotation.remove();
				if (needRemoveSession) {
					if (isRepeatSubmit(request)) {
						logger.warn("please don't repeat submit,[user:" + user.getUsername() + ",url:"
                                + request.getServletPath() + "]");
						return false;
					}
					String requestType = request.getHeader("X-Requested-With");
					if (!"XMLHttpRequest".equals(requestType)) {  //如果是ajax提交，则不清楚session中的token值
						request.getSession(false).removeAttribute("token");
					}
				}
			}
		}
		return true;
	}
	
	public boolean isRepeatSubmit (HttpServletRequest request) {
		String serverToken = (String) request.getSession(true).getAttribute("token");
		if (serverToken == null) {
			return true;
		}
		String clientToken = "";
		/*判断是否为带有文件的表单提交，如果是文件的表单提交，普通的request.getParameter("name")取到的值为null，所以要转换*/
		if (ServletFileUpload.isMultipartContent(request)) {
			clientToken = ((MultipartHttpServletRequest)request).getParameter("token");
		}else {
			clientToken = SpringMvcUtils.getParameter("token");
		}
		if (clientToken == null) {
			return true;
		}
		if (!serverToken.equals(clientToken)) {
			return true;
		}
		return false;
	}

	
}
